<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="发件人地址" prop="senderAddress">
            <el-input
              v-model="formData.senderAddress"
              placeholder="请输入发件人邮箱地址"
              :clearable="true"
              class="mr-2"
            />
            <el-form-item label="" prop="domainId">
              <el-select v-model="formData.domainId" placeholder="请选择地址后缀">
                <el-option
                  v-for="dict in domainList"
                  :key="dict.id"
                  :label="'@' + dict.domainName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="发件人姓名" prop="senderName">
            <el-input
              v-model="formData.senderName"
              placeholder="请输入发件人姓名"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属人" prop="ownerId">
            <el-select v-model="formData.ownerId" placeholder="请选择所属人">
              <el-option
                v-for="dict in ownerList"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="回复人" prop="replyId">
            <el-select
              v-model="formData.replyId"
              placeholder="请选择回复人"
              :empty-values="[0]"
              :value-on-clear="0"
            >
              <el-option
                v-for="dict in replyList"
                :key="dict.id"
                :label="dict.replyName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="SenderEdit" lang="ts">
import * as MarketSettingApi from '@/api/market/marketSetting'
import * as UserApi from '@/api/system/user/user'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const ownerList = ref()
const domainList = ref()
const replyList = ref()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formType = ref('')
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref({
  senderAddress: undefined,
  senderName: undefined,
  ownerId: undefined,
  domainId: undefined,
  replyId: 0
})
const formRules = reactive({
  senderAddress: [{ required: true, message: '请输入发件人地址', trigger: 'change' }],
  senderName: [{ required: true, message: '请输入发件人姓名', trigger: 'change' }],
  ownerId: [{ required: true, message: '请选择所属人', trigger: 'change' }],
  domainId: [{ required: true, message: '请选择发信域名', trigger: 'change' }]
})
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  domainList.value = await MarketSettingApi.domainList({ domainName: undefined })
  replyList.value = await MarketSettingApi.replyList({})
  ownerList.value = await UserApi.getOwnerUser()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.ownerId = wsCache.get(CACHE_KEY.USER).user.id
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MarketSettingApi.singleGetSender(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = async () => {
  formData.value = {
    senderAddress: undefined,
    senderName: undefined,
    ownerId: undefined,
    domainId: undefined,
    replyId: 0
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await MarketSettingApi.createSender(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await MarketSettingApi.updateSender(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
